﻿using System;
using UnityEngine;

namespace Assets.Core
{
    /// <summary>
    /// Manage a bunch of chunks
    /// </summary>
    /// <param name="_width">Width in Chunks</param>
    /// <param name="_height">Height in Chunks</param>
    /// <param name="_depth">Depth in Chunks</param>
    public class ChunkManager
    {
        public ChunkManager(ushort _width, ushort _height, ushort _depth, Vector3 _origin)
        {
            width = _width;
            height = _height;
            depth = _depth;

            chunks = new Chunk[width, height, depth];
        }

        private Chunk[, ,] chunks;
        private readonly ushort width;
        private readonly ushort height;
        private readonly ushort depth;

        public void PlaceBlock(uint _x, uint _y, uint _z, Block _block)
        {
            if (!chunks[_x / width, _y / height, _z / depth].IsEmpty((byte)(_x % width), (byte)(_y % height), (byte)(_z % depth)))
            {
                Debug.LogWarning(String.Format("Block: {0};{1};{2} is already placed", _x, _y, _z));
                return;
            }

            chunks[_x / width, _y / height, _z / depth].ChunkData[_x % width, _y % height, _z % depth] = _block;
            chunks[_x / width, _y / height, _z / depth].ChunkData[_x % width, _y % height, _z % depth].CreateBlock();
        }

        public void RemoveBlock(uint _x, uint _y, uint _z)
        {
            if (chunks[_x / width, _y / height, _z / depth].IsEmpty((byte)(_x % width), (byte)(_y % height), (byte)(_z % depth)))
            {
                Debug.LogWarning(String.Format("Block: {0};{1};{2} is already removed", _x, _y, _z));
                return;
            }

            chunks[_x / width, _y / height, _z / depth].ChunkData[_x % width, _y % height, _z % depth] = null;
            chunks[_x / width, _y / height, _z / depth].ChunkData[_x % width, _y % height, _z % depth].DestroyBlock();
        }
    }
}
